package com.liao.member.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.liao.common.constant.SessionEnum;
import com.liao.common.entity.member.CartEntity;
import com.liao.common.entity.member.UserEntity;
import com.liao.common.entity.product.ProductEntity;
import com.liao.common.entity.product.SkuEntity;
import com.liao.common.utils.PageUtils;
import com.liao.common.utils.Result;
import com.liao.common.vo.member.CartChangeReq;
import com.liao.common.vo.member.CartDetailVo;
import com.liao.common.vo.member.CartReq;
import com.liao.member.feign.ProductFeignService;
import com.liao.member.service.CartService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;


/**
 * 购物车
 *
 * @author liao
 * @email 2858015963@qq.com
 * @date 2025-03-11 08:42:54
 * <p>
 * todo 接口未测试
 */
@RestController
@RequestMapping("member/cart")
public class CartController {
    @Autowired
    private CartService cartService;

    @Autowired
    private ProductFeignService productFeignService;


    /**
     * @ignore 列表
     */
    @RequestMapping("/list")
    public PageUtils<CartEntity> list(@RequestParam Map<String, Object> params) {
        return cartService.queryPage(params);

    }


    /**
     * @ignore 信息
     */
    @RequestMapping("/info/{id}")
    public CartEntity info(@PathVariable("id") Integer id) {
        return cartService.getById(id);

    }

    /**
     * @ignore 保存
     */
    @RequestMapping("/save")
    public void save(@RequestBody CartEntity cart) {
        cartService.save(cart);

    }

    /**
     * @ignore 修改
     */
    @RequestMapping("/update")
    public void update(@RequestBody CartEntity cart) {
        cartService.updateById(cart);

    }

    /**
     * @ignore 删除
     */
    @RequestMapping("/delete")
    public void delete(@RequestBody Integer[] ids) {
        cartService.removeByIds(Arrays.asList(ids));
    }

    /**
     * 加入购物车
     */
    @PostMapping("/addCart")
    public void addCart(@RequestBody CartReq cartReq) {
        if (!StpUtil.isLogin()) {
            throw new RuntimeException("请先登录");
        }
        Integer memberId = StpUtil.getLoginIdAsInt();
        CartEntity cartEntity = new CartEntity();
        cartEntity.setCount(cartReq.getCount());
        cartEntity.setSkuId(cartReq.getSkuId());
        cartEntity.setMemberId(memberId);
        cartEntity.setSelected(0);
        cartService.save(cartEntity);
    }

    /**
     * 获取购物车列表
     */
    @GetMapping("/getCart")
    public List<CartDetailVo> getCart() {
        if (!StpUtil.isLogin()) {
            throw new RuntimeException("请先登录");
        }
        UserEntity user = (UserEntity) StpUtil.getSession().get(SessionEnum.USER_INFO_KEY);

        List<CartEntity> list = cartService.list(new QueryWrapper<CartEntity>().eq("member_id", user.getUserId()));

        List<CartDetailVo> cartDetailVos = new ArrayList<>();
        for (CartEntity cartEntity : list) {
//            获取sku信息
            Result<SkuEntity> result = productFeignService.info(String.valueOf(cartEntity.getSkuId()));
            SkuEntity skuInfo = result.getData();
//            获取商品基本信息
            Result<ProductEntity> productEntityResult = productFeignService.baseInfo(skuInfo.getProductId());
            ProductEntity productEntityResultData = productEntityResult.getData();

            CartDetailVo cartDetailVo = new CartDetailVo();
            cartDetailVo.setId(cartEntity.getId());
            cartDetailVo.setSelected(cartEntity.getSelected());
            cartDetailVo.setCount(cartEntity.getCount());
            cartDetailVo.setMemberId(user.getUserId());
//拷贝数据
            BeanUtils.copyProperties(skuInfo, cartDetailVo);
            BeanUtils.copyProperties(productEntityResultData, cartDetailVo);

            cartDetailVos.add(cartDetailVo);
        }


        return cartDetailVos;
    }

    /**
     * 删除/清空购物车单品
     *
     * @param ids
     */
    @PostMapping("/deleteCart")
    public void deleteCart(@RequestParam("ids") List<Integer> ids) {
        cartService.removeByIds(ids);
    }


    /**
     * 修改购物车单品
     *
     * @param skuId        商品sku id
     * @param crtChangeReq 修改请求参数对象
     */
    @PostMapping("/changeCart/{skuId}")
    public void changeCart(@PathVariable("skuId") Integer skuId, @RequestBody CartChangeReq crtChangeReq) {

        CartEntity cartEntity = new CartEntity();
        cartEntity.setSkuId(skuId);
        if (crtChangeReq.getCount() != null) {
            cartEntity.setCount(crtChangeReq.getCount());

        }
        if (crtChangeReq.getSelected() != null) {
            cartEntity.setSelected(crtChangeReq.getSelected());
        }

        cartService.update(cartEntity, new QueryWrapper<CartEntity>().eq("sku_id", skuId));
    }

    /**
     * 修改购物车选中状态
     *
     * @param selected 选中状态
     */
    @PostMapping("/changeSeleted")
    public void changeSeleted(@RequestBody Integer selected) {
        if (!StpUtil.isLogin()) {
            throw new RuntimeException("请先登录");
        }
        Integer memberId = StpUtil.getLoginIdAsInt();
        List<CartEntity> list = cartService.list(new QueryWrapper<CartEntity>());
        list.forEach(cartEntity -> {
            cartEntity.setSelected(selected);
        });
        cartService.updateBatchById(list);

    }


}
